import { useEffect, useState } from "react";

export type BasketItem = {
  itemId: number;
  quantity: number;
};

const useBasket = () => {
  const [selected, setSelected] = useState<BasketItem[]>([]);

  // Функция для загрузки корзины из LocalStorage
  useEffect(() => {
    const storedBasket = localStorage.getItem("basket");
    if (storedBasket) {
      setSelected(JSON.parse(storedBasket));
    }
  }, []);

  const clearBucket = () => {
    setSelected([]);
    localStorage.removeItem("basket");
  };

  const addItemToBasket = (itemId: number) => {
    setSelected((prevBasket) => {
      const itemIndex = prevBasket.findIndex((item) => item.itemId === itemId);

      if (itemIndex !== -1) {
        const updatedBasket = [...prevBasket];
        updatedBasket[itemIndex].quantity += 1;
        localStorage.setItem("basket", JSON.stringify(updatedBasket));
        return updatedBasket;
      }

      const out = [...prevBasket, { itemId, quantity: 1 }];
      localStorage.setItem("basket", JSON.stringify(out));
      return out;
    });
  };

  const findQuantity = (itemId: number) => {
    const item = selected.find((item) => item.itemId === itemId);

    return item?.quantity;
  };

  return {
    selected,
    addItemToBasket,
    findQuantity,
    clearBucket,
  };
};

export default useBasket;
